package ext.generic.project.reports;



import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import wt.doc.WTDocument;
import wt.epm.EPMDocument;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.collections.WTCollection;
import wt.org.WTPrincipal;
import wt.part.WTPart;
import wt.projmgmt.admin.Project2;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTStandardDateFormat;

import com.ptc.projectmanagement.deliverable.PlanDeliverable;
import com.ptc.projectmanagement.deliverable.PlanDeliverableLink;
import com.ptc.projectmanagement.plan.Duration;
import com.ptc.projectmanagement.plan.Plan;
import com.ptc.projectmanagement.plan.PlanActivity;
import com.ptc.projectmanagement.plan.PlanHelper;
import com.ptc.projectmanagement.plan.Plannable;
import com.ptc.projectmanagement.plannable.PlannableHelper;
import com.ptc.projectmanagement.plannable.PrecedenceConstraint;
import com.ptc.projectmanagement.plannable.PrecedenceType;
import com.ptc.projectmanagement.util.NumberFormattingUtils;

import ext.com.iba.IBAUtil;

/**
 * 项目报表
 * @author John
 *
 */
public class ProjectPlanReportCommand {
	private static boolean VERBOSE;
	private static String CLASSNAME = ProjectPlanReportCommand.class.getName();
	private static String codebalocation;
	private static WTProperties wtProperties = null;
	//报表名称
	private static final String JOURNAL_NAME = "ProPlanExpForm";
	//报表名称
	private static final String JOURNAL_NAMES = "ProPlanExpFormWithoutDeliverables";
	static
	{
		try
		{
			wtProperties = WTProperties.getLocalProperties();
			VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.generic.project.reports.verbose", false);
			codebalocation = wtProperties.getProperty("wt.codebase.location", "");
		}
		catch (Throwable throwable)
		{
			throw new ExceptionInInitializerError(throwable);
		}
	}
	 /**
	 *输出调试信息
	 */
	private static void outDebugInfo(String info)
	{
		if(VERBOSE){
			System.out.println(CLASSNAME+">>>"+info);
		}
	}
	
	/**
	 * 导出项目计划（带交付物）
	 * @param proj
	 * @param oid
	 * @param response
	 * @throws WTException
	 * @throws IOException
	 */
	public static void getProjectPlanAll(Project2 proj, String oid, HttpServletResponse response) throws WTException, IOException {
		//项目名称
		String projName = proj.getName();
		//项目代号
		String projNumber = proj.getProjectNumber();
		System.out.println("projNumber==========>"+projNumber);
		//项目状态
		String projState = proj.getCtmState().getFullDisplay();
		//项目所有者
		String projOwner = ((WTPrincipal)proj.getOwner()).getName();
		System.out.println("projOwner==========>"+projOwner);
		String fileName = projName + "_" + JOURNAL_NAME +".xls";
		response.setContentType("application/x-msdownload");
		// 定义打印出来后的报表名
		response.setHeader("Content-disposition", "attachment; filename="
				+ fileName);
		OutputStream os = response.getOutputStream();
		String filePath = codebalocation + File.separator+"ext"+File.separator+"generic"+File.separator+"project"+File.separator+"reports"+File.separator+"ProjectPlanAllTemplate.xls";
		
		HashMap table=new HashMap();
		table.put("活动ID", "1");
		table.put("活动名称", "2");
		table.put("工期", "3");
		table.put("预计开始时间", "4");
		table.put("预计完成时间", "5");
		table.put("实际开始时间", "6");
		table.put("实际完成时间", "7");
		table.put("完成百分比", "8");
		table.put("状况", "9");
		table.put("风险", "10");
		table.put("前后置关系", "11");
		table.put("所有者", "12");
		
		table.put("名称", "13");
		table.put("主题", "14");
		table.put("生命周期状态", "15");
		table.put("交付完成百分比", "16");
		table.put("开始时间", "17");
		table.put("完成时间", "18");
		table.put("交付所有者", "19");
		table.put("最后期限", "20");
		table.put("里程碑", "21");
		
		// 读取excel文件
		File file = new File(filePath);
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
		HSSFWorkbook hwb = new HSSFWorkbook(fs);
		HSSFSheet sheet = hwb.getSheetAt(0);
		HSSFRow row = null;
		HSSFCell cell = null;

		
		//获取模板结构信息
		ProjectReportUtil.getTemplateLocation(sheet, table);
		//获取模板位置
		String idY=table.get("活动ID").toString();
		String nameY=table.get("活动名称").toString();
		String workDateY=table.get("工期").toString();
		String esStartTimeY=table.get("预计开始时间").toString();
		String esCompTimeY=table.get("预计完成时间").toString();
		String actualStartTimeY=table.get("实际开始时间").toString();
		String actualcompTimeY=table.get("实际完成时间").toString();
		String percentCompY=table.get("完成百分比").toString();
		String stateY=table.get("状况").toString();
		String risksY=table.get("风险").toString();
		String befAndAftY=table.get("前后置关系").toString();
		String ownerY=table.get("所有者").toString();	
		
		String submitNameY=table.get("名称").toString();
		String submitTitleY=table.get("主题").toString();
		String submitStateY=table.get("生命周期状态").toString();
		String submitPercentCompY=table.get("交付完成百分比").toString();
		String submitStartTimeY=table.get("开始时间").toString();
		String submitCompTimeY=table.get("完成时间").toString();
		String submitOwnerY=table.get("交付所有者").toString();
		String submitDeadTimeY=table.get("最后期限").toString();
		String isMildStoneY=table.get("里程碑").toString();
		

		String percentPlan = null;
		Plan plan = null;
		ReferenceFactory rf= new ReferenceFactory();
		plan = (Plan) PlanHelper.service.getPlan((ObjectReference)rf.getReference(proj));
		Double dpercentPlan = plan.getPercentWorkComplete();
		String ss = NumberFormattingUtils.removeZeroDecimal(dpercentPlan);
		percentPlan = ss +"%";
		
		PlannableHelper planhelper = new PlannableHelper();
		Class theActivityClass = com.ptc.projectmanagement.plan.PlanActivity.class;
		QuerySpec querySpec = new QuerySpec();
		int index1 = querySpec.appendClassList(theActivityClass, true);
		// projId = oid.substring(30, 36);
		String[] stringArray = null;
		String projId = "";
		outDebugInfo("==oid=="+oid);
		stringArray = oid.split(":");
		if(stringArray.length>1){
			projId = stringArray[2];
		}
		outDebugInfo("==projId=="+projId);
		SearchCondition condition1 = new SearchCondition(theActivityClass,
				PlanActivity.CONTAINER_ID, SearchCondition.EQUAL, new Long(projId));
		querySpec.appendWhere(condition1);
		/*OrderBy orderby = new OrderBy(new ClassAttribute(theActivityClass, "thePersistInfo.createStamp"), true);
		querySpec.appendOrderBy(orderby);*/
		OrderBy orderby = new OrderBy(new ClassAttribute(theActivityClass, PlanActivity.LINE_NUMBER), false);
		querySpec.appendOrderBy(orderby);
		outDebugInfo("querySpec = ==== " + querySpec);

		QueryResult queryresult = PersistenceHelper.manager.find(querySpec);
		outDebugInfo("queryresult.size() " + queryresult.size());

		PlanActivity planActivity = null;
		// 输出内容
		int i = 2;
		
		// 遍历所有计划活动
		while (queryresult.hasMoreElements()) {
			String id = null;
			String activityName = null;
			//String activityOwner = null;
			String endDate = "";
			String percentFinished = "";
			planActivity = (com.ptc.projectmanagement.plan.PlanActivity) ((Object[]) queryresult.nextElement())[0];
			// 获取当前任务的所有交付项
			if(planActivity.getLineNumber()==0){
				if(VERBOSE){
					System.out.println("跳过计划根节点:"+planActivity.getName());
				}
				continue;
			}
			WTCollection wtc = planhelper.service.getPlanDeliverableLinks(planActivity);
			// 输出活动ID			
			id = "" + planActivity.getLineNumber();
			//活动名称
			activityName = planActivity.getName();
			String isMileStone="";
			if(planActivity.isMilestone()){
				isMileStone="是";
			}else{
				isMileStone="否";
			}
			
			//工期
		
			Duration duration= planActivity.getDuration();
			double dValue= duration.getDuration(duration.getDurationFormat());
			dValue=ProjectReportUtil.roundHalfUp(dValue);//四舍五入
			String workDate= dValue + " " + duration.getDurationFormat().getDisplay();
			
			//预计开始时间
			Timestamp esStartTime=planActivity.getStartDate();
			String esStartTimeStr="";
			if(esStartTime!=null){
				esStartTime.setHours(esStartTime.getHours()+8);
				esStartTimeStr= WTStandardDateFormat.format(esStartTime,"yyyy年MM月dd日");
			}
			//预计完成时间
			Timestamp esCompTime=planActivity.getFinishDate();
			String esCompTimeStr="";
			if(esCompTime!=null){
				esCompTime.setHours(esCompTime.getHours()+8);
				esCompTimeStr= WTStandardDateFormat.format(esCompTime,"yyyy年MM月dd日");
			}
			
			//实际开始时间
			String actualStartTimeStr="";
			Timestamp actualStartTime=(Timestamp) IBAUtil.getIBAValue(planActivity, "ActualStartTime");
			if(actualStartTime!=null){
				actualStartTime.setHours(actualStartTime.getHours()+8);
				actualStartTimeStr= WTStandardDateFormat.format(actualStartTime,"yyyy年MM月dd日");
			}	
			
			//实际完成时间
			String actualCompletionTimeStr="";
			Timestamp actualCompletionTime=(Timestamp) IBAUtil.getIBAValue(planActivity, "ActualCompletionTime");
			if(actualCompletionTime!=null){
				actualCompletionTime.setHours(actualCompletionTime.getHours()+8);
				actualCompletionTimeStr= WTStandardDateFormat.format(actualCompletionTime,"yyyy年MM月dd日");
			}	
			
			
			//完成百分比
			Double dpercentFinished = planActivity.getPercentWorkComplete();
			outDebugInfo("dpercentFinished>>>1>>"+dpercentFinished);
			dpercentFinished=dpercentFinished/100;//除以100
			dpercentFinished=ProjectReportUtil.roundHalfUp(dpercentFinished);//四舍五入
			outDebugInfo("dpercentFinished>>>>2>>"+dpercentFinished);
			dpercentFinished=dpercentFinished*100;//乘以100
			String s1 = NumberFormattingUtils.removeZeroDecimal(dpercentFinished);
			percentFinished = s1+"%";
			
			//状况
			String stateStr=planActivity.getHealthStatusType().getDisplay();
			
			//风险
			String risksStr=planActivity.getRiskType().getDisplay();
			
			//前后置关系
			String beforeLine="";
			//获取前置任务;
			 WTCollection collection= PlannableHelper.service.listPrecedenceConstraintsBySuccessor(planActivity);
			 Iterator iterator=collection.persistableIterator();
			 while(iterator.hasNext()){
				 //System.out.println("*****************"+iterator.next());
				 
				 PrecedenceConstraint constraint= (PrecedenceConstraint)iterator.next();
					Plannable predecessor= constraint.getPredecessor();
					PrecedenceType precedenceType= constraint.getPrecedenceType();
					Duration scheduleOffset= constraint.getScheduleOffset();
					if(beforeLine.length()<=0)
					{
						if(predecessor.getLineNumber()==0){
							continue;
						}
						beforeLine= "" + predecessor.getLineNumber();
					}
					else
					{
						if(predecessor.getLineNumber()==0){
							continue;
						}
						beforeLine= beforeLine + "," + predecessor.getLineNumber();
					}
			 }
			 
			
			//所有者
			String ownerShip=planActivity.getOwnership().getOwner().getObject()==null?"":planActivity.getOwnership().getOwner().getDisplayName();
			
			outDebugInfo("wtc>>>"+wtc.size());
			if(wtc.size()>0){
				
				// 输出活动ID和名称			
				id = "" + planActivity.getLineNumber();
				activityName = planActivity.getName();
				//activityOwner = planActivity.getOwnership().getOwner().getFullName();
				//完成时间
				Timestamp getEndDate = planActivity.getFinishDate();
				if(getEndDate!=null){
					getEndDate.setHours(getEndDate.getHours()+8);
					endDate= WTStandardDateFormat.format(getEndDate,"yyyy年MM月dd日");
				}
				
				row = sheet.getRow(i);
				cell = row.getCell(Integer.valueOf(idY));//活动ID
				cell.setCellValue(id);
				
				cell = row.getCell(Integer.valueOf(nameY));//活动名称
				cell.setCellValue(activityName);
				
				//工期
				cell = row.getCell(Integer.valueOf(workDateY));
				cell.setCellValue(workDate);
				
				//预计开始时间
				cell = row.getCell(Integer.valueOf(esStartTimeY));
				cell.setCellValue(esStartTimeStr);
				
				//预计完成时间
				cell = row.getCell(Integer.valueOf(esCompTimeY));
				cell.setCellValue(esCompTimeStr);
				
				//实际开始时间
				cell = row.getCell(Integer.valueOf(actualStartTimeY));
				cell.setCellValue(actualStartTimeStr);
				
				//实际完成时间
				cell = row.getCell(Integer.valueOf(actualcompTimeY));
				cell.setCellValue(actualCompletionTimeStr);
				
				//完成百分比
				cell = row.getCell(Integer.valueOf(percentCompY));
				cell.setCellValue(percentFinished);
				
				//状况
				cell = row.getCell(Integer.valueOf(stateY));
				cell.setCellValue(stateStr);
				
				//风险
				cell = row.getCell(Integer.valueOf(risksY));
				cell.setCellValue(risksStr);
				
				//前后置关系
				cell = row.getCell(Integer.valueOf(befAndAftY));
				cell.setCellValue(beforeLine);
				
				//所有者
				cell = row.getCell(Integer.valueOf(ownerY));
				cell.setCellValue(ownerShip);
				
				//是否是里程碑
				cell = row.getCell(Integer.valueOf(isMildStoneY));//isMildStoneYc
				cell.setCellValue(isMileStone);
				
				Iterator it = wtc.iterator();
				
				// 有交付项的活动才输出
				while (it.hasNext()) {	
					String objId = "";
					String objName = "";
					String objState = "";
					
					Object objItor = it.next();
					ObjectReference ref = (ObjectReference) objItor;
					PlanDeliverableLink pdl = (PlanDeliverableLink) ref.getObject();
					PlanDeliverable planDelive=pdl.getPlanDeliverable();
					System.out.println("startDate>>>>>"+IBAUtil.getIBAValue(planDelive, "startDate"));
					// 输出可交付名称
					String needDelivName = planDelive.getName();
					
					outDebugInfo("needDelivName>>>>"+needDelivName);
					
					//获取开始时间 开始
					boolean flag1 = false;
		            PlanActivity planactivity1 = null;
		            Plan plan1 = null;
		            Plannable plannable = (Plannable)planDelive.getParent();
		            if(plannable instanceof Plan)
		            {
		                plan1 = (Plan)plannable;
		                outDebugInfo("plannable instanceof Plan");
		            } else
		            if(plannable instanceof PlanActivity)
		            {
		            	
		                PlanActivity planactivity2 = (PlanActivity)plannable;
		                plan1 = (Plan)planactivity2.getParent();
		                outDebugInfo("plannable instanceof PlanActivity");
		            }else {
		            	
		            	outDebugInfo("plannable instanceof others:"+plannable);
		            }
		            outDebugInfo(""+plan1);
		            flag1 = plan1.isLinkDeliverable();
		            if(flag1)
		            {
		                WTCollection wtcollection = PlannableHelper.service.getPlanDeliverableLinks(planDelive);
		                for(Iterator iteratorT = wtcollection.persistableIterator(); iteratorT.hasNext();)
		                {
		                    PlanDeliverableLink plandeliverablelink = (PlanDeliverableLink)iteratorT.next();
		                    planactivity1 = plandeliverablelink.getPlanActivity();
		                }

		            }
		            outDebugInfo("planactivity1:"+planactivity1);
		           
		          //获取开始时间 结束
					
					//交付物所有者
					String needDelivOwner = planDelive.getOwnership().getOwner().getFullName();
					outDebugInfo("needDelivOwner>>>>"+needDelivOwner);
					
					System.out.println("finishDate>>>>>"+IBAUtil.getIBAValue(planDelive, "finishDate"));
					//planDelive.getPersistInfo().get
					String dStartTimeStr = "";
					String completeTime = "";
					if(planactivity1!=null){
						//开始时间
						Timestamp dStartTime =planactivity1.getStartDate();
						
						//outDebugInfo("dStartTime>>>>"+dStartTime);
						
						if(dStartTime!=null){
							//format time:yyyy-MM-dd HH:mm:ss
							dStartTime.setHours(dStartTime.getHours()+8);
							dStartTimeStr= WTStandardDateFormat.format(dStartTime,"yyyy年MM月dd日");
						}
						outDebugInfo("dStartTimeStr>>>>"+dStartTimeStr);
						
						//完成时间
						Timestamp dcompleteTime = planactivity1.getFinishDate();
						
						//outDebugInfo("dcompleteTime>>>>"+dcompleteTime);
						
						if(dcompleteTime!=null){
							//format time:yyyy-MM-dd HH:mm:ss
							dcompleteTime.setHours(dcompleteTime.getHours()+8);
							completeTime= WTStandardDateFormat.format(dcompleteTime,"yyyy年MM月dd日");
						}
						outDebugInfo("completeTime>>>>"+completeTime);
					}
					
					
					
					
					//交付物完成百分比
					Double needDelivPoint = planDelive.getPercentComplete();
					needDelivPoint=ProjectReportUtil.roundHalfUp(needDelivPoint);//四舍五入
					String s2 = NumberFormattingUtils.removeZeroDecimal(needDelivPoint);
					String strNeedDelivPoint = s2+"%";
					outDebugInfo("strNeedDelivPoint>>>>"+strNeedDelivPoint);
					
					//最后期限
					Timestamp deadTime=planDelive.getDeadline();
					
					String deadTimeStr = "";
					if(deadTime!=null){
						//format time:yyyy-MM-dd HH:mm:ss
						deadTime.setHours(deadTime.getHours()+8);
						deadTimeStr= WTStandardDateFormat.format(deadTime,"yyyy年MM月dd日");
					}
					outDebugInfo("deadTimeStr>>>>"+deadTimeStr);
					
					Object obj = planDelive.getSubject().getObject();
					//主题
					String subTitle="";
					if (obj instanceof WTDocument) {
						WTDocument wtDoc  = (WTDocument) obj;
						// 输出文档名称和状态
						objId = wtDoc.getNumber();
						objName = wtDoc.getName();
						objState = wtDoc.getState().getState().getDisplay();
						subTitle=wtDoc.getDisplayIdentity().toString();
						outDebugInfo("objName>>>>"+objName+">>>objState>>>"+objState);

					} else if (obj instanceof EPMDocument) {
						EPMDocument epmDoc = (EPMDocument) obj;
						// 输出文档名称和状态
						objId = epmDoc.getNumber();
						objName = epmDoc.getName();
						objState = epmDoc.getState().getState().getDisplay();
						subTitle=epmDoc.getDisplayIdentity().toString();
						outDebugInfo("objName>>>>"+objName+">>>objState>>>"+objState);
						
					} else if(obj instanceof WTPart){
						WTPart wtPart = (WTPart) obj;
						// 输出文档名称和状态
						objId = wtPart.getNumber();
						objName = wtPart.getName();
						objState = wtPart.getState().getState().getDisplay();
						subTitle=wtPart.getDisplayIdentity().toString();
						outDebugInfo("objName>>>>"+objName+">>>objState>>>"+objState);
					}
					
					/*// 样式设置
					if (objState != null && objState.equals("RELEASED") == false) {
						cell = row.getCell(10);
						HSSFCellStyle cs = hwb.createCellStyle();
						cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
						cs.setFillForegroundColor(new HSSFColor.RED().getIndex());
						cell.setCellStyle(cs);
					}*/
					//**********************输出可交付结果*****************************
					row = sheet.getRow(i);
					//名称
					cell = row.getCell(Integer.valueOf(submitNameY));
					cell.setCellValue(needDelivName);
					
					//主题
					cell = row.getCell(Integer.valueOf(submitTitleY));
					cell.setCellValue(subTitle);
					
					//生命周期状态
					cell = row.getCell(Integer.valueOf(submitStateY));
					cell.setCellValue(objState);
					
					//交付完成百分比
					cell = row.getCell(Integer.valueOf(submitPercentCompY));
					cell.setCellValue(strNeedDelivPoint);
					
					//开始时间
					cell = row.getCell(Integer.valueOf(submitStartTimeY));
					cell.setCellValue(dStartTimeStr);
					
					//完成时间
					cell = row.getCell(Integer.valueOf(submitCompTimeY));
					cell.setCellValue(completeTime);
					
					//交付所有者
					cell = row.getCell(Integer.valueOf(submitOwnerY));
					cell.setCellValue(needDelivOwner);
					
					//最后期限
					cell = row.getCell(Integer.valueOf(submitDeadTimeY));
					cell.setCellValue(deadTimeStr);
					
					
					i++;
				}
				
				outDebugInfo("" + id + "," + activityName);
			}
		}
		sheet.autoSizeColumn(( short )1);
		// 输出数据
		hwb.write(os); // 将文件流写入对象
		os.close();
	}
	
	/**
	 * 项目计划导出报表（不带可交付结果）
	 * @param proj
	 * @param oid
	 * @param response
	 * @throws WTException
	 * @throws IOException
	 */
	public static void getProjectPlanWithoutSubmit(Project2 proj, String oid, HttpServletResponse response) throws WTException, IOException {
		//项目名称
		String projName = proj.getName();
		//项目代号
		String projNumber = proj.getProjectNumber();
		System.out.println("projNumber==========>"+projNumber);
		//项目状态
		String projState = proj.getCtmState().getFullDisplay();
		//项目所有者
		String projOwner = ((WTPrincipal)proj.getOwner()).getName();
		System.out.println("projOwner==========>"+projOwner);
		String fileName = projName + "_" +JOURNAL_NAMES +".xls";
		response.setContentType("application/x-msdownload");
		// 定义打印出来后的报表名
		response.setHeader("Content-disposition", "attachment; filename="
				+ fileName);
		OutputStream os = response.getOutputStream();
		String filePath = codebalocation + File.separator+"ext"+File.separator+"generic"+File.separator+"project"+File.separator+"reports"+File.separator+"ProjectPlanWithoutSubmitTemplate.xls";
		
		HashMap table=new HashMap();
		table.put("活动ID", "1");
		table.put("活动名称", "2");
		table.put("工期", "3");
		table.put("预计开始时间", "4");
		table.put("预计完成时间", "5");
		table.put("实际开始时间", "6");
		table.put("实际完成时间", "7");
		table.put("完成百分比", "8");
		table.put("状况", "9");
		table.put("风险", "10");
		table.put("前后置关系", "11");
		table.put("所有者", "12");
		table.put("里程碑", "13");
		
		// 读取excel文件
		File file = new File(filePath);
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
		
		HSSFWorkbook hwb = new HSSFWorkbook(fs);
		HSSFSheet sheet = hwb.getSheetAt(0);
		HSSFRow row = null;
		HSSFCell cell = null;
		//获取模板结构信息
		ProjectReportUtil.getTemplateLocation(sheet, table);
		//获取模板位置
		String idY=table.get("活动ID").toString();
		String nameY=table.get("活动名称").toString();
		String workDateY=table.get("工期").toString();
		String esStartTimeY=table.get("预计开始时间").toString();
		String esCompTimeY=table.get("预计完成时间").toString();
		String actualStartTimeY=table.get("实际开始时间").toString();
		String actualcompTimeY=table.get("实际完成时间").toString();
		String percentCompY=table.get("完成百分比").toString();
		String stateY=table.get("状况").toString();
		String risksY=table.get("风险").toString();
		String befAndAftY=table.get("前后置关系").toString();
		String ownerY=table.get("所有者").toString();
		String isMildStoneY=table.get("里程碑").toString();
		
		String percentPlan = null;
		Plan plan = null;
		ReferenceFactory rf= new ReferenceFactory();
		plan = (Plan) PlanHelper.service.getPlan((ObjectReference)rf.getReference(proj));
		Double dpercentPlan = plan.getPercentWorkComplete();
		dpercentPlan=ProjectReportUtil.roundHalfUp(dpercentPlan);//四舍五入
		String ss = NumberFormattingUtils.removeZeroDecimal(dpercentPlan);
		percentPlan = ss +"%";
		
		PlannableHelper planhelper = new PlannableHelper();
		Class theActivityClass = com.ptc.projectmanagement.plan.PlanActivity.class;
		QuerySpec querySpec = new QuerySpec();
		int index1 = querySpec.appendClassList(theActivityClass, true);
		// projId = oid.substring(30, 36);
		String[] stringArray = null;
		String projId = "";
		outDebugInfo("==oid=="+oid);
		stringArray = oid.split(":");
		if(stringArray.length>1){
			projId = stringArray[2];
		}
		outDebugInfo("==projId=="+projId);
		SearchCondition condition1 = new SearchCondition(theActivityClass,
				PlanActivity.CONTAINER_ID, SearchCondition.EQUAL, new Long(projId));
		querySpec.appendWhere(condition1);
		/*OrderBy orderby = new OrderBy(new ClassAttribute(theActivityClass, "thePersistInfo.createStamp"), true);
		querySpec.appendOrderBy(orderby);*/
		OrderBy orderby = new OrderBy(new ClassAttribute(theActivityClass, PlanActivity.LINE_NUMBER), false);
		querySpec.appendOrderBy(orderby);
		outDebugInfo("querySpec = ==== " + querySpec);

		QueryResult queryresult = PersistenceHelper.manager.find(querySpec);
		outDebugInfo("queryresult.size() " + queryresult.size());

		
		// 输出内容
		int i = 2;
		String id = null;
		String activityName = null;
		//String activityOwner = null;
		String endDate = "";
		String percentFinished = "";
		// 遍历所有计划活动
		while (queryresult.hasMoreElements()) {
			PlanActivity planActivity = (com.ptc.projectmanagement.plan.PlanActivity) ((Object[]) queryresult.nextElement())[0];
			if(planActivity.getLineNumber()==0){
				if(VERBOSE){
					System.out.println("跳过计划根节点:"+planActivity.getName());
				}
				continue;
			}
			// 获取当前任务的所有交付项
			WTCollection wtc = planhelper.service.getPlanDeliverableLinks(planActivity);
			wtc.persistableCollection();
			String isMileStone="";
			if(planActivity.isMilestone()){
				isMileStone="是";
			}else{
				isMileStone="否";
			}
			//如有交付物 跳过
			if(wtc.size()>0){
				continue;
			}else{
					// 输出活动ID			
					id = "" + planActivity.getLineNumber();
					//活动名称
					activityName = planActivity.getName();
					
					//工期
				
					Duration duration= planActivity.getDuration();
					double dValue= duration.getDuration(duration.getDurationFormat());
					dValue=ProjectReportUtil.roundHalfUp(dValue);//四舍五入
					String workDate= dValue + " " + duration.getDurationFormat().getDisplay();
					
					//预计开始时间
					Timestamp esStartTime=planActivity.getStartDate();
					String esStartTimeStr="";
					if(esStartTime!=null){
						esStartTime.setHours(esStartTime.getHours()+8);
						esStartTimeStr= WTStandardDateFormat.format(esStartTime,"yyyy年MM月dd日");
					}
					//预计完成时间
					Timestamp esCompTime=planActivity.getFinishDate();
					String esCompTimeStr="";
					if(esCompTime!=null){
						esCompTime.setHours(esCompTime.getHours()+8);
						esCompTimeStr= WTStandardDateFormat.format(esCompTime,"yyyy年MM月dd日");
					}
					
					//实际开始时间
					String actualStartTimeStr="";
					Timestamp actualStartTime=(Timestamp) IBAUtil.getIBAValue(planActivity, "ActualStartTime");
					if(actualStartTime!=null){
						actualStartTime.setHours(actualStartTime.getHours()+8);
						actualStartTimeStr= WTStandardDateFormat.format(actualStartTime,"yyyy年MM月dd日");
					}	
					
					//实际完成时间
					String actualCompletionTimeStr="";
					Timestamp actualCompletionTime=(Timestamp) IBAUtil.getIBAValue(planActivity, "ActualCompletionTime");
					if(actualCompletionTime!=null){
						actualCompletionTime.setHours(actualCompletionTime.getHours()+8);
						actualCompletionTimeStr= WTStandardDateFormat.format(actualCompletionTime,"yyyy年MM月dd日");
					}	
					
					/*//完成时间
					Timestamp getEndDate = planActivity.getFinishDate();
					if(getEndDate!=null){
						endDate= WTStandardDateFormat.format(getEndDate,"yyyy年MM月dd日");
					}*/
					//完成百分比
					Double dpercentFinished = planActivity.getPercentWorkComplete();
					outDebugInfo("dpercentFinished>>>1>>"+dpercentFinished);
					dpercentFinished=dpercentFinished/100;//除以100
					dpercentFinished=ProjectReportUtil.roundHalfUp(dpercentFinished);//四舍五入
					outDebugInfo("dpercentFinished>>>>2>>"+dpercentFinished);
					dpercentFinished=dpercentFinished*100;//乘以100
					String s1 = NumberFormattingUtils.removeZeroDecimal(dpercentFinished);
					percentFinished = s1+"%";
					
					//状况
					String stateStr=planActivity.getHealthStatusType().getDisplay();
					
					//风险
					String risksStr=planActivity.getRiskType().getDisplay();
					
					//前后置关系
					String beforeLine="";
					//获取前置任务;
					 WTCollection collection= PlannableHelper.service.listPrecedenceConstraintsBySuccessor(planActivity);
					 Iterator iterator=collection.persistableIterator();
					 while(iterator.hasNext()){
						 //System.out.println("*****************"+iterator.next());
						 
						 PrecedenceConstraint constraint= (PrecedenceConstraint)iterator.next();
							Plannable predecessor= constraint.getPredecessor();
							PrecedenceType precedenceType= constraint.getPrecedenceType();
							Duration scheduleOffset= constraint.getScheduleOffset();
							if(beforeLine.length()<=0)
							{
								if(predecessor.getLineNumber()==0){
									continue;
								}
								beforeLine= "" + predecessor.getLineNumber();
							}
							else
							{
								if(predecessor.getLineNumber()==0){
									continue;
								}
								beforeLine= beforeLine + "," + predecessor.getLineNumber();
							}
					 }
					 
					
					//所有者
					String ownerShip=planActivity.getOwnership().getOwner().getObject()==null?"":planActivity.getOwnership().getOwner().getDisplayName();
					
					
					
					//String idY=table.get("活动ID").toString();
					//String nameY=table.get("活动名称").toString();
					//String workDateY=table.get("工期").toString();
					//String esStartTimeY=table.get("预计开始时间").toString();
					//String esCompTimeY=table.get("预计完成时间").toString();
					//String actualStartTimeY=table.get("实际开始时间").toString();
					//String actualcompTimeY=table.get("实际完成时间").toString();
					//String percentCompY=table.get("完成百分比").toString();
					//String stateY=table.get("状况").toString();
					//String risksY=table.get("风险").toString();
					//String befAndAftY=table.get("前后置关系").toString();
					//String ownerY=table.get("所有者").toString();
					// 输出到excel中
					row = sheet.getRow(i);
					cell = row.getCell(Integer.valueOf(idY));//活动ID
					cell.setCellValue(id);
					
					cell = row.getCell(Integer.valueOf(nameY));//活动名称
					cell.setCellValue(activityName);
					
					//工期
					cell = row.getCell(Integer.valueOf(workDateY));
					cell.setCellValue(workDate);
					
					//预计开始时间
					cell = row.getCell(Integer.valueOf(esStartTimeY));
					cell.setCellValue(esStartTimeStr);
					
					//预计完成时间
					cell = row.getCell(Integer.valueOf(esCompTimeY));
					cell.setCellValue(esCompTimeStr);
					
					//实际开始时间
					cell = row.getCell(Integer.valueOf(actualStartTimeY));
					cell.setCellValue(actualStartTimeStr);
					
					//实际完成时间
					cell = row.getCell(Integer.valueOf(actualcompTimeY));
					cell.setCellValue(actualCompletionTimeStr);
					
					//完成百分比
					cell = row.getCell(Integer.valueOf(percentCompY));
					cell.setCellValue(percentFinished);
					
					//状况
					cell = row.getCell(Integer.valueOf(stateY));
					cell.setCellValue(stateStr);
					
					//风险
					cell = row.getCell(Integer.valueOf(risksY));
					cell.setCellValue(risksStr);
					
					//前后置关系
					cell = row.getCell(Integer.valueOf(befAndAftY));
					cell.setCellValue(beforeLine);
					
					//所有者
					cell = row.getCell(Integer.valueOf(ownerY));
					cell.setCellValue(ownerShip);
					
					//是否是里程碑
					cell = row.getCell(Integer.valueOf(isMildStoneY));//isMildStoneYc
					cell.setCellValue(isMileStone);
				
				outDebugInfo("" + id + "," + activityName);
			}
			i++;
		}
		sheet.autoSizeColumn(( short )1);
		// 输出数据
		hwb.write(os); // 将文件流写入对象
		os.close();
		
	}
}
